package com.example.demo.compile;

import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User:龙宝
 * Date:2023-10-08
 * Time:16:50
 * 该类时对于执行编译和运行命令的封装
 */
public class CommandExecute {
    /**
     *
     * @param cmd   命令
     * @param stdoutFile   标准结果存放的文件路径及文件名
     * @param stderrFile   标准错误存放的文件路径及文件名
     * @return
     */
    public static int run(String cmd,String stdoutFile,String stderrFile) {
        try {
            //1、通过Runtime类得到Runtime实例，执行exec方法
            Process process = Runtime.getRuntime().exec(cmd);
            int exitCode = process.waitFor();
            //2、获取到标准输出，并写入到指定文件中
            if(stdoutFile != null) {
                InputStream stdoutFrom = process.getInputStream();
                FileOutputStream stdoutTO = new FileOutputStream(stdoutFile);
                while (true) {
                    int ch = stdoutFrom.read();
                    if(ch == -1) {
                        break;
                    }
                    stdoutTO.write(ch);
                }
                stdoutFrom.close();
                stdoutTO.close();
            }
            //3、获取到标准错误，写入指定文件
            if(stderrFile != null) {
                InputStream stderrFrom = process.getErrorStream();
                FileOutputStream stderrTo = new FileOutputStream(stderrFile);
                while (true) {
                    int ch = stderrFrom.read();
                    if(ch == -1) {
                        break;
                    }
                    stderrTo.write(ch);
                }
                stderrFrom.close();
                stderrTo.close();
            }
            //4、子进程结束，拿到子进程的状态码，并返回

            return exitCode;
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
        return 1;
    }
}
